package com.imy.lua.view.floating;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;

;

import com.imy.common.event.FloatingEvent;
import com.imy.common.util.ALog;
import com.imy.common.util.UiUtil;
import com.imy.lua.LuaCore;
import com.imy.lua.R;
import com.imy.touch.event.GeneralEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static android.content.Context.WINDOW_SERVICE;

/**
 * @ProjectName: yuanshen
 * @Package: com.hykb.yuanshenmap.cloudgame.floating
 * @ClassName: QueueFloatingManger
 * @Description: 描述
 * @Author: Imy
 * @CreateDate: 2021/4/9 16:23
 */
public class FloatingManger {
    private static final String TAG = "QueueFloatingManger";
    WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private AbsoluteLayout customLayout;
    private FloatingView floatingView;
    private static volatile FloatingManger floatingManger = new FloatingManger();

    public static FloatingManger get() {
        return floatingManger;
    }

    private Context context;

    private FloatingManger() {
        EventBus.getDefault().register(this);
        windowManager = (WindowManager) LuaCore.get().getContext().getSystemService(WINDOW_SERVICE);
        context = LuaCore.get().getContext();
        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.flags = getFloatingFlag();

        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.x = 0;
        layoutParams.y = 0;
        layoutParams.windowAnimations = R.style.default_style;
        layoutParams.gravity = Gravity.START | Gravity.TOP;

        customLayout = new AbsoluteLayout(context);
        customLayout.setLayoutParams(new ViewGroup.LayoutParams(UiUtil.getDeviceWidth(context),
                UiUtil.getDeviceHeight(context)));
        floatingView = new FloatingView(context);
        floatingView.setTouchListener(new FloatingView.TouchListener() {
            @Override
            public void onTouch(MotionEvent event) {
                doOnTouch(event);
            }

        });
        floatingView.measure(0, 0);

        layoutParams.x = 0;
        int deviceWidth = UiUtil.getDeviceHeight(context) / 4;
        layoutParams.y = deviceWidth;
        customLayout.addView(floatingView);
    }

    public void start() {
        try {
            windowManager.removeView(customLayout);
        } catch (Exception e) {

        }
        windowManager.addView(customLayout, layoutParams);

    }

    public WindowManager getWindowManager() {
        return windowManager;
    }

    public void setOri(int ori) {
        this.ori = ori;
    }

    private int ori = Configuration.ORIENTATION_PORTRAIT;
    private float downX;
    private float downY;

    private void doOnTouch(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getRawX();
                downY = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                float rawX = event.getRawX();
                float rawY = event.getRawY();
                if (Math.abs(downX - rawX) < 10 && Math.abs(downY - rawY) < 10) {
                    //过滤掉抖动
                    break;
                }
                //直接更新xy
                //int x;
                //int width = floatingView.getMeasuredWidth() / 2;
                //if (ori == Configuration.ORIENTATION_LANDSCAPE) {
                //  x = (int) event.getRawX() - floatingView.getMeasuredWidth();
                //} else {
                //  x = (int) event.getRawX() - width;
                //}
                //Log.i(TAG, " width:" + width);
                //
                //if (x < 0) {
                //  x = 0;
                //}
                //layoutParams.x = x;
                int y;
                if (ori == Configuration.ORIENTATION_LANDSCAPE) {
                    int i = floatingView.getMeasuredHeight() / 2;
                    y = (int) event.getRawY() - i;
                } else {
                    y = (int) event.getRawY() - floatingView.getMeasuredHeight();
                }
                if (y < 0) {
                    y = 0;
                }
                layoutParams.y = y;
                windowManager.updateViewLayout(customLayout, layoutParams);
                break;
            case MotionEvent.ACTION_UP:
                rawX = event.getRawX();
                rawY = event.getRawY();
                if (Math.abs(downX - rawX) < 10 && Math.abs(downY - rawY) < 10) {
                    onClicked();
                }
                break;
        }
    }

    private void onClicked() {
        //弹出窗口
        floatingView.openOptionOrClose();
    }

    private int getFloatingFlag() {
        return WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
    }

    public FloatingView getFloatingView() {
        return floatingView;
    }

    public void onDestroy() {
        removeView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GeneralEvent event) {
        floatingView.getConsoleView().addLog(event.msg);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(FloatingEvent event) { //隐藏显示都会造成程序死循环 目前未知 但该功能并不影响
        ALog.ti("Event:"+event.action+"Thread:"+Thread.currentThread());

//        if (event.action == FloatingEvent.ACTION_HIDE) {
//            removeView();
      if (event.action == FloatingEvent.ACTION_SHOW) {
            getFloatingView().setVisibility(View.VISIBLE);
        }
    }

    public void removeView() {
        try {
            windowManager.removeView(customLayout);
        } catch (Exception e) {
            //not attached to window manager
        }
    }

    public void setClickedListener(ClickedListener touchListener) {
        this.onCloseListener = touchListener;
    }

    public void stop() {
        removeView();
    }

    public interface ClickedListener {
        void onClicked();
    }

    private ClickedListener onCloseListener;
}